package com.example.flowermall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.flowermall.entity.*;
import com.example.flowermall.mapper.*;
import com.example.flowermall.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.flowermall.service.IProductService;
import com.example.flowermall.service.IntegralProductService;
import com.example.flowermall.service.MembersService;
import com.example.flowermall.util.OrderIdUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaoman
 * @since 2023-09-06
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements IOrderService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserAddressMapper addressMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    ShoppingCartMapper cartMapper;
    @Autowired
    ProductMapper productMapper;
    @Autowired
    IProductService productService;

    private final MembersService membersService;
    private final IntegralProductService integralProductService;

    public OrderServiceImpl(MembersService membersService, IntegralProductService integralProductService) {
        this.membersService = membersService;
        this.integralProductService = integralProductService;
    }

    @Override
    public void insertOrder(Orders orders) {
        orderMapper.insert(orders);
    }

    @Override
    public Orders getOrderById(Integer id) {
        return orderMapper.selectById(id);
    }

    @Override
    public void updateOrder(Orders orders) {
        orderMapper.updateById(orders);
    }

    @Override
    public void deleteOrder(String orderId) {
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getOrderId,orderId);
        Orders orders = orderMapper.selectOne(queryWrapper);
        orders.setDeleteStatus("1");
        orderMapper.updateById(orders);
    }

    @Override
    public Orders createOrder(CreateOrder createOrder) {
        Orders orders = new Orders();
        int num= 0;
        orders.setDeliveryType(createOrder.getDeliveryType());
        if(createOrder.getDeliveryType().equals(1)){
            UserAddress userAddress = addressMapper.selectById(createOrder.getAddressId());
            orders.setReceiverName(userAddress.getReceiverName());
            orders.setReceiverPhone(userAddress.getReceiverPhone());
            orders.setReceiverAddress(userAddress.getProvince()+userAddress.getCity()+userAddress.getArea()+userAddress.getAddress());
        }
        orders.setDeleteStatus("0");
        if(createOrder.getCartId()!=null){
            for(int i=0;i<createOrder.getCartId().size();i++){
                ShoppingCart shoppingCart = cartMapper.selectById(createOrder.getCartId().get(i));;
                num +=shoppingCart.getCartNum()*Double.parseDouble(String.valueOf(shoppingCart.getProductPrice()));
            }
        }
        if(createOrder.getProductId()!=null){
            if(createOrder.getIsIntegral().equals(1)){
                IntegralProduct integralProduct = integralProductService.queryById(createOrder.getProductId());
                num += createOrder.getProdCount()*Double.parseDouble(String.valueOf(integralProduct.getPrice()));
            }else {
                Product product = productMapper.selectById(createOrder.getProductId());
                num+=createOrder.getProdCount()*Double.parseDouble(String.valueOf(product.getPrice()));
            }
        }
        orders.setTotalPrice(BigDecimal.valueOf(num));
        if(createOrder.getRemarks().equals("余额充值")){
            orders.setTotalPrice(createOrder.getTotal());
            orders.setOrderName("余额充值");
        }
        orders.setUserId(createOrder.getUserId());
        orders.setCreateTime(LocalDateTime.now());
        orders.setOrderId(OrderIdUtil.createOrderId());
        orders.setOrderRemark(createOrder.getRemarks());
        orders.setOrderStatus("1");
        if(createOrder.getIsPay().equals(1)){
            //待发货
            orders.setOrderStatus("2");
        }
        orderMapper.insert(orders);
        int count=0;
        if(createOrder.getCartId()!=null){
            for(int i=0;i<createOrder.getCartId().size();i++){
                OrderItem orderItem = new OrderItem();
                Product product = productMapper.selectById(cartMapper.selectById(createOrder.getCartId().get(i)).getProductId());
                orderItem.setOrderId(orders.getOrderId());
                orderItem.setProductId(product.getProductId());
                orderItem.setProductName(product.getProductName());
                orderItem.setProductPrice(product.getPrice());
                orderItem.setTotalAmount(cartMapper.selectById(createOrder.getCartId().get(i)).getCartNum()*cartMapper.selectById(createOrder.getCartId().get(i)).getProductPrice().longValue());
                orderItem.setBuyTime(LocalDateTime.now());
                orderItem.setBuyCounts(cartMapper.selectById(createOrder.getCartId().get(i)).getCartNum());
                count =orderItemMapper.insert(orderItem);
            }
            for(int j=0;j<createOrder.getCartId().size();j++){
                cartMapper.deleteById(createOrder.getCartId().get(j));
            }
            if(count==1)
            {
                return this.getByOrderId(orders.getOrderId());
            }
        }
        OrderItem item = new OrderItem();
        item.setOrderId(orders.getOrderId());
        item.setProductId(createOrder.getProductId());
        if(createOrder.getIsIntegral().equals(1)){
            IntegralProduct integralProduct = integralProductService.queryById(createOrder.getProductId());
            item.setProductName(integralProduct.getProductName());
            item.setProductPrice(BigDecimal.valueOf(integralProduct.getPrice()));
            item.setTotalAmount(createOrder.getProdCount()*integralProduct.getPrice().longValue());
        }else  {
            if(!ObjectUtils.isEmpty(createOrder.getProductId())){
                Product product = productMapper.selectById(createOrder.getProductId());
                item.setProductName(product.getProductName());
                item.setProductPrice(product.getPrice());
                item.setTotalAmount(createOrder.getProdCount()*product.getPrice().longValue());
            }else {
                item.setProductName("余额充值");
                item.setProductPrice(createOrder.getTotal());
                item.setTotalAmount(createOrder.getTotal().longValue());
            }
        }
        item.setBuyTime(LocalDateTime.now());
        item.setBuyCounts(createOrder.getProdCount());
        count=orderItemMapper.insert(item);
        if(count==1)
        {
            return this.getByOrderId(orders.getOrderId());
        }
        return null;
    }
    @Override
    public Orders getByOrderId(String orderId) {
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getOrderId,orderId);
        Orders orders = orderMapper.selectOne(queryWrapper);
        if(orders==null){
            return null;
        }
        LambdaQueryWrapper<OrderItem> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.eq(OrderItem::getOrderId,orderId);
        List<OrderItem> orderItems = orderItemMapper.selectList(queryWrapper1);
        if(orderItems==null){
            return orders;
        }
        orders.setOrderItem(orderItems);
        return orders;
    }

    @Override
    public Orders getByOrderId(String orderId, int i) {
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getOrderId,orderId);
        Orders orders = orderMapper.selectOne(queryWrapper);
        if(orders==null){
            return null;
        }
        LambdaQueryWrapper<OrderItem> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.eq(OrderItem::getOrderId,orderId);
        List<OrderItem> orderItems = orderItemMapper.selectList(queryWrapper1);
        if(orderItems==null){
            return orders;
        }
        Integer num = membersService.getByOrderId(orderId);
        for(OrderItem item:orderItems){
            Integer productId = item.getProductId();
            if(i==1||num==1){
                IntegralProduct integralProduct = integralProductService.getGoodsById(productId);
                item.setProductImg(integralProduct.getProductUrl());
            }else {
                Product goodsById = productService.getGoodsById(productId);
                item.setProductImg(goodsById.getProductUrl());
            }
        }
        orders.setOrderItem(orderItems);
        return orders;
    }

    @Override
    public List<Orders> getListByUserId(Integer userId, String orderStatus) {
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        if(orderStatus.equals("0")){
            queryWrapper.eq(Orders::getUserId,userId).orderByDesc(Orders::getId);
            queryWrapper.eq(Orders::getDeleteStatus,"0");
        }
        else {
            queryWrapper.eq(Orders::getUserId,userId).orderByDesc(Orders::getId);
            queryWrapper.eq(Orders::getOrderStatus,orderStatus);
            queryWrapper.eq(Orders::getDeleteStatus,"0");
        }
        List<Orders> orders = orderMapper.selectList(queryWrapper);
        for(int i=0;i<orders.size();i++){
            LambdaQueryWrapper<OrderItem> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrderItem::getOrderId,orders.get(i).getOrderId());
            List<OrderItem> orderItems = orderItemMapper.selectList(queryWrapper1);
            for(OrderItem orderItem : orderItems){
                Product product = productService.getGoodsById(orderItem.getProductId());
                if(product!=null){
                    orderItem.setProductImg(product.getProductUrl());
                }
            }
            orders.get(i).setOrderItem(orderItems);
        }
        return orders;
    }

    @Override
    public void confirmOrder(String orderId) {
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getOrderId,orderId);
        Orders orders = orderMapper.selectOne(queryWrapper);
        orders.setOrderStatus("5");
        orderMapper.updateById(orders);
    }

    @Override
    public List<Orders> select(Orders orders) {
        return orderMapper.select(orders);
    }

    @Override
    public List<Orders> selectRevenueT() {
        return orderMapper.selectRevenueT();
    }

    @Override
    public List<Orders> selectUnpaidT() {
        return orderMapper.selectUnpaidT();
    }

    @Override
    public List<Orders> selectRevenueY() {
        return orderMapper.selectRevenueY();
    }

    @Override
    public List<Orders> selectUnpaidY() {
        return orderMapper.selectUnpaidY();
    }

    @Override
    public Map<String, Integer> getCount(Integer userId) {
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId,userId);
        queryWrapper.ne(Orders::getDeleteStatus,"1");
        List<Orders> orders = orderMapper.selectList(queryWrapper);
        Integer unpay=0;
        Integer payed=0;
        Integer consignment=0;
        for (Orders order : orders){
            if(Objects.equals(order.getOrderStatus(), "1")){
                unpay++;
            }
            if (Objects.equals(order.getOrderStatus(), "2")){
                payed++;
            }
            if (Objects.equals(order.getOrderStatus(), "3")){
                consignment++;
            }
        }
        HashMap<String, Integer> map = new HashMap<>();
        map.put("unpay",unpay);
        map.put("payed",payed);
        map.put("consignment",consignment);
        return map;
    }
}
